import React from 'react';
import '@wangeditor/editor/dist/css/style.css';
import { Editor, Toolbar } from '@wangeditor/editor-for-react';
import type { IDomEditor, IEditorConfig, IToolbarConfig } from '@wangeditor/editor';
import CUploadView from '@/components/common/CUpload/CUploadView';
import { message } from 'antd';
import { setContent } from '@/services/admin/common/api';
import HtmlView from './components/HtmlView';
import './index.css';
interface TypeProps {
  value: any;
  height?: number;
  width?: number;
  onChange: any;
  placeholder?: string;
  visiblePreview?: boolean;
  editor: IDomEditor | null;
  toolbarConfig?: Partial<IToolbarConfig>;
  editorConfig?: Partial<IEditorConfig>;
}
let modalVisibleImageViewModal: CUploadView | null = null;
let modalVisibleHtmlViewModal: HtmlView | null = null;
let insertFnLs: any = null;
let uploadStatus: any = 1;
class CWangEditor extends React.Component<any, TypeProps> {
  constructor(props: TypeProps) {
    super(props);
    this.state = {
      value: props.value,
      height: props.height || 500,
      onChange: props.onChange,
      placeholder: props.placeholder || '请输入...',
      visiblePreview: false,
      editor: props.editor || null,
      // 工具栏配置
      toolbarConfig: props.toolbarConfig || {
        insertKeys: {
          index: 0,
          keys: ['getHtmlView', 'saveRemotePicturesInfo', 'insertFormula', 'uploadAttachment'],
        },
      },
      // 编辑器配置
      editorConfig: props.editorConfig || {
        placeholder: '请输入内容...',
        scroll: true,
        maxLength: 10000,
        onMaxLength: (editor: IDomEditor) => {
          editor.alert('输入内容以超出最大限制', 'error');
        },
        // customPaste: (editor: IDomEditor, event: ClipboardEvent): boolean => {
        //   // TS 语法
        //   // editorConfig.customPaste = (editor, event) => {                                       // JS 语法

        //   // event 是 ClipboardEvent 类型，可以拿到粘贴的数据
        //   // 可参考 https://developer.mozilla.org/zh-CN/docs/Web/API/ClipboardEvent

        //   // const html = event.clipboardData.getData('text/html') // 获取粘贴的 html
        //   // const text = event.clipboardData.getData('text/plain') // 获取粘贴的纯文本
        //   // const rtf = event.clipboardData.getData('text/rtf') // 获取 rtf 数据（如从 word wsp 复制粘贴）

        //   // 同步
        //   // editor.insertText('xxx');

        //   // // 异步
        //   // setTimeout(() => {
        //   //   editor.insertText('yy');
        //   // }, 1000);

        //   // // 阻止默认的粘贴行为
        //   // event.preventDefault();
        //   // return false;

        //   // 继续执行默认的粘贴行为
        //   return true;
        // },
        customAlert: (s: string, t: string) => {
          switch (t) {
            case 'success':
              message.success(s);
              break;
            case 'info':
              message.info(s);
              break;
            case 'warning':
              message.warning(s);
              break;
            case 'error':
              message.error(s);
              break;
            default:
              message.info(s);
              break;
          }
        },
        hoverbarKeys: {
          formula: {
            menuKeys: ['editFormula'], // “编辑公式”菜单
          },
          link: {
            menuKeys: [
              'editLink',
              'unLink',
              'viewLink', // 默认的配置可以通过 `editor.getConfig().hoverbarKeys.link` 获取
              'convertToLinkCard', // 增加 '转为链接卡片'菜单
            ],
          },
        },
        MENU_CONF: {
          uploadImage: {
            async customBrowseAndUpload(insertFn: any) {
              modalVisibleImageViewModal?.show();
              uploadStatus = 1;
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              insertFnLs = insertFn;
            },
          },
          uploadAttachment: {
            async customBrowseAndUpload(insertFn: any) {
              modalVisibleImageViewModal?.show();
              uploadStatus = 2;
              // eslint-disable-next-line @typescript-eslint/no-unused-vars
              insertFnLs = insertFn;
            },
          },
          convertToLinkCard: {
            // 自定义获取 link-card 信息，可选
            // 返回 { title, iconImgSrc }
            async getLinkCardInfo(linkText: string, linkUrl: string) {
              return { title: linkText, iconImgSrc: linkUrl, linkUrl: linkUrl };
              // 1. 可通过 iframe 加载网页，然后获取网页 title 和其中的图片
              // 2. 服务端获取（有些网页会设置 `X-Frame-Options` ，无法通过 iframe 加载）
              // // 模拟异步返回
              // return new Promise((resolve) => {
              //   setTimeout(() => {
              //     const info = { title: linkText, iconImgSrc: '' };
              //     resolve(info);
              //   }, 100);
              // });
            },
          },
          getHtmlView: {
            async onClick(editor: IDomEditor) {
              modalVisibleHtmlViewModal?.show(editor.getHtml());
            },
          },
          saveRemotePicturesInfo: {
            async onClick(editor: IDomEditor) {
              const hide = message.loading('解析中..', 0);
              const htmlContent = editor.getHtml();
              const res = await setContent(htmlContent);
              if (res.status === 20000) {
                hide();
                this.setState({ value: res.data.content });
                editor?.updateView();
                message.success(res.message);
              }
            },
          },
        },
      },
    };
  }
  render() {
    const { value, height, editor } = this.state;
    return (
      <>
        <HtmlView
          ref={(com) => {
            modalVisibleHtmlViewModal = com;
          }}
          onChange={(html: any) => {
            this.setState({ value: html });
            editor?.updateView();
          }}
        />
        <CUploadView
          ref={(com) => {
            modalVisibleImageViewModal = com;
          }}
          key={9}
          count={9}
          onChange={async (data: any) => {
            if (data.length) {
              for (let i = 0; i < data.length; i++) {
                if (uploadStatus == 1) {
                  insertFnLs(data[i].http_url, '', data[i].http_url);
                } else {
                  insertFnLs(data[i].http_url, data[i].http_url);
                }
              }
            }
          }}
        />
        <div style={{ border: '1px solid #ccc', zIndex: 100 }}>
          <Toolbar
            editor={editor}
            defaultConfig={this.state.toolbarConfig}
            mode="default"
            style={{ borderBottom: '1px solid #ccc' }}
          />
          <Editor
            defaultConfig={this.state.editorConfig}
            value={value}
            onCreated={(e) => {
              this.setState({ editor: e });
            }}
            onChange={(editorData) => {
              this.state.onChange(editorData.getHtml());
              this.setState({ value: editorData.getHtml() });
            }}
            mode="default"
            style={{ minHeight: height + 'px', overflowY: 'hidden' }}
          />
        </div>
      </>
    );
  }
}
export default CWangEditor;
